const {
	app,
	BrowserWindow,
	Menu,
	MenuItem,
	screen,
	Tray,
	ipcMain,
	webFrame,
} = require('electron')
const path = require('path')
const ipc_modules = require('./modules/ipc')
let win
const right_menu = new Menu()
const LOAD_URL = 'http://pakchoi.windystory.com/keke/admin'

const createWindow = () => {
	win = new BrowserWindow({
		frame: false,
		show: true,
		resizable: true,
		width: 520,
		height: 320,
		icon: path.join(__dirname, './logo/index.png'),
		webPreferences: {
			devTools: true,
			nodeIntegration: true,
			contextIsolation: false,
			zoomFactor: 1,
			defaultEncoding: 'UTF-8',
		},
		backgroundColor: '#FFF',
	})
	Menu.setApplicationMenu(null)
	win.loadURL(LOAD_URL)
	win.once('ready-to-show', () => {
		win.webContents.setZoomFactor(1)
	})
	win.webContents.on('zoom-changed', (e, zd) => {
		win.webContents.zoomLevel += zd === 'in' ? 1 : -1
	})
}

// close
app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') app.quit()
})

// open
app.whenReady().then(() => {
	createWindow()
	app.on('activate', () => {
		if (BrowserWindow.getAllWindows().length === 0) createWindow()
	})
	// 系统托盘
	let tray = new Tray(path.join(__dirname, './logo/index.png'))
	const contextMenu = Menu.buildFromTemplate([
		{
			label: '最小化',
			click: () => {
				win.minimize()
			},
		},
		{
			label: '退出',
			click: () => {
				win.close()
			},
		},
	])
	tray.setToolTip('一柯小白菜')
	tray.setContextMenu(contextMenu)
	tray.on('click', () => {
		win.isMinimized() && win.restore()
	})
	// 右键菜单
	let win_is_resizable
	for (const menuitem of [
		{
			label: '刷新',
			click: () => {
				win.webContents.send('reload')
			},
		},
		{
			label: 'Open Tool',
			click: () => {
				win.webContents.openDevTools()
			},
		},
		{ type: 'separator' },
		{
			label: '关闭',
			click: () => {
				win.close()
			},
		},
	])
		right_menu.append(new MenuItem(menuitem))
	win.webContents.on('context-menu', (e, { x, y }) => {
		right_menu.popup({ window: win, x, y })
	})
})
